package com.cn.service;

import com.cn.entity.KrpanoScene;
import com.cn.utlis.IBase;
import com.cn.vo.KrpanoHotspotRelationVo;
import com.cn.vo.KrpanoIdVo;
import com.cn.vo.KrpanoResultVo;
import com.cn.vo.krpanoSceneRelationVo;
import com.cn.vo.KrpanoProjectVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: chenyuncong
 * @Date: 2020/5/14 22:02
 */
@Service
@Slf4j
public class KrpanoSceneServiceImpl extends IBase<KrpanoScene> implements KrpanoSceneService {


    @Override
    public void ergodicFile(String path) throws Exception {
        File file = new File(path);
        System.out.println(file.getName());
        String[] fileName = file.getName().split("-");
        Long projectId = Long.parseLong(fileName[0]);
        String ng = null;
        if (fileName.length == 2) {
            ng = fileName[1];
        }
        if (ng != null) {
            if (ng.equals("n")) {
                return;
            }
        }
        List<KrpanoResultVo> list = new ArrayList<>();
        if (file.isDirectory()) {
            File[] filelist = file.listFiles();
            File dFile = null;
            for (int i = 0; i < filelist.length; i++) {
                dFile = filelist[i];
                if (dFile.isFile()) {
                    String dFIleName = dFile.getName();
                    String[] dateRe = dFIleName.split("-");
                    if (dateRe.length == 2) {
//                      private Long projectId;  //项目id
//                      private Long krpanoSceneId; //场景id
//                      private String time;  //时间戳
//                      private String name;  //场景名字
                        String time = dateRe[0];
                        String title = dateRe[1].substring(0, dateRe[1].indexOf("."));
                        KrpanoResultVo k = new KrpanoResultVo();
                        k.setProjectId(projectId);
                        k.setTime(time);
                        k.setTitle(title);
                        list.add(k);
//                      System.out.println(k);
//                      System.out.println(dFile);
                    }

                }
            }

            updateKrpanoSceneBatch(list, projectId);
        }

    }

    public void updateKrpanoSceneBatch(List<KrpanoResultVo> list, Long projectId) throws Exception {
        System.out.println(projectId);

        List<krpanoSceneRelationVo> rList = getkrpanoSceneRelationListByProjectId(projectId);  //scene_id、 description 场景名字
        List<KrpanoHotspotRelationVo> hList = getKrpanoHotspotRelationListByProjectId(projectId); //根据热点获取 场景名字 ， krpano_scene_id、scene_name
        KrpanoProjectVo krpanoProject = getKrpanoProjectById(projectId);

        for (KrpanoResultVo vo : list) {
            for (krpanoSceneRelationVo r : rList) {
                if (r.getDescription().equals(vo.getTitle())) {
                    if(vo.getKrpanoSceneId()==null){
                        vo.setKrpanoSceneId(r.getScene_id());
                    }
                }
            }
            for (KrpanoHotspotRelationVo h : hList) {
                if (h.getKrpano_scene_id().equals(vo.getKrpanoSceneId())) {
                    if(vo.getName()==null){
                        vo.setName(h.getScene_name());
                    }
                }
            }
            vo.setUserId(Long.parseLong(krpanoProject.getCreation_user()));
        }

        list.forEach(o -> {
            System.out.println(o);
            updateKrpanoSceneByTime(o);
        });
        System.out.println(list.size());
    }

    public void updateKrpanoSceneByTime(KrpanoResultVo vo) {
        String sql = "update krpano_scene_batch2 set " +
                "krpano_scene_id=" + vo.getKrpanoSceneId() + ", " +
                "title='" + vo.getTitle() + "'," +
                "`name`='" + vo.getName() + "'," +
                "is_valid=1," +
                "creation_user=3295 where max_url like '%" + vo.getTime() + "%'";
//        System.out.println(sql);
        this.getJdbcTemplate().execute(sql);
//        return null;
    }

    public List<KrpanoHotspotRelationVo> getKrpanoHotspotRelationListByProjectId(Long projectId) throws Exception {
        String sql = "select h.scene_name,h.krpano_scene_id from krpano_hotspot_relation h where " +
                "h.project_id=" + projectId + " and h.is_valid=1 group by h.scene_name,h.krpano_scene_id";
        return this.getList(sql, KrpanoHotspotRelationVo.class);
    }

    //    public
    //获取场景id和对应的场景名字
    public List<krpanoSceneRelationVo> getkrpanoSceneRelationListByProjectId(Long projectId) throws Exception {
        String sql = "select r.id,r.scene_id,r.description from krpano_scene_relation r where r.project_id=" + projectId;
        return this.getList(sql, krpanoSceneRelationVo.class);
    }


    public KrpanoProjectVo getKrpanoProjectById(Long id) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("select p.id,p.creation_date,p.creation_user,p.title,p.cover_url ");
        sql.append("from krpano_project p where 1=1 and p.id=").append(id);
        return this.get(sql.toString(), KrpanoProjectVo.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateKrpanoSceneAllById(Long ksId, Long Index) throws Exception {
        if (ksId > 1481) {
            return;
        }
        String layerSql = "select h.id,h.scene_id from krpano_sha_pan_layer h where h.id>=70787 and h.scene_id=" + ksId;
        List<KrpanoIdVo> layerIdLIst = this.getList(layerSql, KrpanoIdVo.class);
        log.info("layerIdLIst:{}", layerIdLIst.toString());
        layerIdLIst.forEach(o -> o.setScene_id(Index));
        log.info("layerIdLIst:{}", layerIdLIst.toString());

        String relationSql = "select h.id,h.scene_id from krpano_scene_relation h where  h.creation_date >='2020-5-14 00:00:00' and h.scene_id=" + ksId;
        List<KrpanoIdVo> relationIdLIst = this.getList(relationSql, KrpanoIdVo.class);
        log.info("relationIdLIst:{}", relationIdLIst.toString());
        relationIdLIst.forEach(o -> o.setScene_id(Index));
        log.info("relationIdLIst:{}", relationIdLIst.toString());

        String hotspotSql = "select h.id,h.krpano_scene_id scene_id from krpano_hotspot_relation h where h.creation_date >='2020-5-14 00:00:00' and h.krpano_scene_id=" + ksId;
        List<KrpanoIdVo> hotspotIdLIst = this.getList(hotspotSql, KrpanoIdVo.class);
        log.info("hotspotIdLIst:{}", hotspotIdLIst.toString());
        hotspotIdLIst.forEach(o -> o.setScene_id(Index));
        log.info("hotspotIdLIst:{}", hotspotIdLIst.toString());

        updateKrpanoScene(ksId, Index);
        updateLayer(layerIdLIst);
        updateRelation(relationIdLIst);
        updateHotspot(hotspotIdLIst);
    }


    @Override
    public List<KrpanoProjectVo> getKrpanoProjectList() throws Exception {
//        String sql ="select p.id,p.creation_date,p.creation_user,p.title,p.cover_url " +
//                "from krpano_project p where 1=1 " +
//                "and p.creation_date>='2020-05-01 00:00:00' " +
//                "and p.creation_date<='2020-05-13 23:59:59' ";

        StringBuffer sql = new StringBuffer();
        sql.append("select p.id,p.creation_date,p.creation_user,p.title,p.cover_url ");
        sql.append("from krpano_project p where 1=1 and is_valid=1 ");
        sql.append("and p.creation_date>='2020-03-24 00:00:00' and p.creation_date<='2020-5-13 23:59:59' ");
        sql.append("and p.id in( ");
        sql.append("select aa.project_id from ( ");
        sql.append("select r.project_id from krpano_scene_relation r  left join krpano_scene s on s.id=r.scene_id where 1=1 ");
        sql.append("and r.creation_date>='2020-04-01 00:00:00' and r.creation_date<='2020-04-30 23:59:59' ");
        sql.append("and s.id is null group by r.project_id ) aa ");
        sql.append(")");
        return this.getList(sql.toString(), KrpanoProjectVo.class);
    }

    //用于查询某天的缩略图
    @Override
    public List<KrpanoScene> getKrpanoSceneDateList(String startTime, String endTime) throws Exception {
        String sql = "select s.creation_date,s.min_url from krpano_scene_batch2 s " +
                "where s.creation_date>='" + startTime + "' " +
                "and s.creation_date<='" + endTime + "' " +
                "order by s.creation_date ";
        return this.getList(sql.toString(), KrpanoScene.class);
    }

    public void updateLayer(List<KrpanoIdVo> layerIdLIst) {
        layerIdLIst.forEach(u -> {
            try {
                this.update("update krpano_sha_pan_layer set scene_id=:scene_id where id=:id", u);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void updateRelation(List<KrpanoIdVo> relationIdLIst) {
        relationIdLIst.forEach(u -> {
            try {
                this.update("update krpano_scene_relation set scene_id=:scene_id where id=:id", u);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void updateHotspot(List<KrpanoIdVo> hotspotIdLIst) {
        hotspotIdLIst.forEach(u -> {
            try {
                this.update("update krpano_hotspot_relation set krpano_scene_id=:scene_id where id=:id", u);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void updateKrpanoScene(Long krpanoId, Long index) {
        this.getJdbcTemplate().execute("update krpano_scene set id=" + index + " where id=" + krpanoId);
    }


}
